# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/7/10
# @File   : IC_Past12MonsAddedTinyCompLoanCnt.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:过去12个月新增小额贷款笔数
code:IC_Past12MonsAddedTinyCompLoanCnt
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''



import datetime
from dateutil.relativedelta import relativedelta
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = IC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def formatDate(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None

def IC_Past12MonsAddedTinyCompLoanCnt():
    try:
        # three_month_ago = (datetime.datetime.now() - relativedelta(months=3)).strftime("%Y%m%d")
        twelve_month_ago = (datetime.datetime.now() - datetime.timedelta(days=12*30)).strftime("%Y%m%d")
        ICRLoanInfo002Loan = getTable('ICRLoanInfo002*Loan')

        if ICRLoanInfo002Loan is None:
            return u'缺失值'
        elif ICRLoanInfo002Loan == [{}]:
            return 0
        else:
            flag = []
            count = 0
            for i in ICRLoanInfo002Loan:
                financeType = i.get('financeType')
                openDate = i.get('openDate')

                if financeType in null_type_list or openDate in null_type_list or formatDate(openDate) is None:
                    flag.append(None)
                    continue
                else:
                    if financeType == u'小额信贷公司' and formatDate(openDate) > twelve_month_ago:
                        count += 1
                    else:
                        pass
            if len(flag) == len(ICRLoanInfo002Loan):
                return u'缺失值'
            else:
                return count
    except:
        return u'缺失值'

result = IC_Past12MonsAddedTinyCompLoanCnt()

